﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharedGenomics.Core;
using SharedGenomics.Workbench.PresentationModel;

namespace SharedGenomics.Workbench.Models
{
    public class WatchListModel
    {
        private ICollection<WatchListItem> _items;
        private IEqualityComparer<string> _markerComparer;

        public WatchListModel()
        {
            this._items = new List<WatchListItem>();
            this._markerComparer = StringComparer.InvariantCultureIgnoreCase;
        }

        public void LoadIdentifiers(IEnumerable<string> markers)
        {
            this._items.Clear();

            if (markers != null)
            {
                foreach (string id in markers.Where(s => s != null).Distinct(this.MarkerComparer))
                {
                    this._items.Add(new WatchListItem() { Name = id, IsFlagged = false });
                }
            }

            this.ListChanged.Raise(this);
        }

        public void ClearIdentifiers()
        {
            this._items.Clear();
            this.ListChanged.Raise(this);
        }

        public void SyncWith<T>(IEnumerable<T> data, Func<T, string> mapFunc)
        {
            mapFunc.ThrowIfNull("mapFunc");

            this._items = this._items.GroupJoin(data ?? Enumerable.Empty<T>(),
                                                wli => wli.Name,
                                                mapFunc,
                                                (wli, results) => new WatchListItem() { Name = wli.Name, IsFlagged = results.Count() > 0 },
                                                this.MarkerComparer).ToList();

            this.ListChanged.Raise(this);
        }

        public IEnumerable<WatchListItem> Items
        {
            get { return this._items; }
        }

        public IEqualityComparer<string> MarkerComparer
        {
            get { return this._markerComparer; }
            set
            {
                this._markerComparer = value ?? StringComparer.InvariantCultureIgnoreCase;
            }
        }

        public event EventHandler ListChanged;
    }
}
